<template>
  <div class="table-container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input v-model="searchValue" placeholder="输入商品名称、类别或状态搜索" clearable @clear="handleSearchClear"
        @input="handleSearchInput" class="search-input">
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd" class="add-button">添加商品</el-button>
    </div>

    <!-- 商品表格 -->
    <el-table ref="tableRef" :data="currentPageData" stripe style="width: 100%" class="goods-table"
      @selection-change="handleSelectionChange">
      <!-- 复选框列 -->
      <el-table-column type="selection" width="55" />

      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column label="图片">
        <template #default="scope">
          <el-image v-if="scope.row.img" :src="getImagePath(scope.row.img)"
            :preview-src-list="[getImagePath(scope.row.img)]" fit="cover" class="product-image">
            <template #error>
              <div class="image-error">
                <el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-image>
          <div v-else class="no-image">
            <el-icon>
              <Picture />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" />

      <!-- 类别列 - 添加筛选下拉框 -->
      <el-table-column prop="category" label="分类" :filters="categoryFilters" :filter-method="filterCategory">
        <template #header>
          <div class="category-header">
            <span>分类</span>
            <el-dropdown trigger="click" @command="handleCategoryFilter">
              <el-icon :size="16">
                <ArrowDown />
              </el-icon>
              <el-dropdown-menu>
                <el-dropdown-item command="all">所有类别</el-dropdown-item>
                <el-dropdown-item v-for="category in uniqueCategories" :key="category" :command="category">
                  {{ category }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>

        <template #default="scope">
          {{ scope.row.category }}
        </template>
      </el-table-column>

      <el-table-column prop="price" label="价格">
        <template #default="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="count" label="库存" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === '在售' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="商品图片">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="handleImageUpload"
            :before-upload="beforeImageUpload">
            <img v-if="form.img" :src="getImagePath(form.img)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="ID">
          <el-input v-model="form.id" :disabled="isEditing"></el-input>
        </el-form-item>
        <el-form-item label="名称" required>
          <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="类别" required>
          <el-input v-model="form.category" placeholder="请输入商品类别"></el-input>
        </el-form-item>
        <el-form-item label="价格" required>
          <el-input v-model.number="form.price" type="number" min="0">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库存" required>
          <el-input v-model.number="form.count" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="在售" value="在售" />
            <el-option label="缺货" value="缺货" />
          </el-select>
        </el-form-item>
        <!-- 创建时间框的长度要统一 -->
        <el-form-item label="创建时间">
          <el-date-picker style="width: 100%" v-model="form.createdAt" type="date" placeholder="选择日期"
            value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
      <!-- 分页 -->
    </el-dialog>

    <div class="pagination">
      <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
        :current-page="currentPage" @current-change="handleCurrentChange"></el-pagination>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 商品数据
const goods = ref([
  {
    "id": "1",
    "img": "public/img/phone.jpg",
    "name": "Apple iPhone 14 Pro",
    "category": "智能手机",
    "price": 8999,
    "count": 125,
    "status": "在售",
    "createdAt": "2023-03-15"
  },
  {
    "id": "2",
    "img": "public/img/phone.jpg",
    "name": "小米13 Ultra",
    "category": "智能手机",
    "price": 5999,
    "count": 87,
    "status": "在售",
    "createdAt": "2023-04-20"
  },
  {
    "id": "3",
    "img": "public/img/computer.jpg",
    "name": "联想小新Pro 16",
    "category": "笔记本电脑",
    "price": 6499,
    "count": 42,
    "status": "在售",
    "createdAt": "2023-02-10"
  },
  {
    "id": "4",
    "img": "public/img/p1.jpg",
    "name": "索尼WH-1000XM5",
    "category": "耳机",
    "price": 2299,
    "count": 156,
    "status": "在售",
    "createdAt": "2023-05-05"
  },
  {
    "id": "5",
    "img": "public/img/computer.jpg",
    "name": "戴尔U2723QX显示器",
    "category": "电脑配件",
    "price": 4299,
    "count": 23,
    "status": "缺货",
    "createdAt": "2023-01-18"
  },
  {
    "id": "6",
    "img": "public/img/computer.jpg",
    "name": "华为MateBook X Pro",
    "category": "笔记本电脑",
    "price": 8999,
    "count": 68,
    "status": "在售",
    "createdAt": "2023-06-12"
  },
  {
    "id": "7",
    "img": "public/img/phone.jpg",
    "name": "三星Galaxy S23",
    "category": "智能手机",
    "price": 5699,
    "count": 0,
    "status": "缺货",
    "createdAt": "2023-03-28"
  },
  {
    "id": "8",
    "img": "public/img/p1.jpg",
    "name": "Bose QuietComfort 45",
    "category": "耳机",
    "price": 1999,
    "count": 92,
    "status": "在售",
    "createdAt": "2023-04-03"
  },
  {
    "id": "9",
    "img": "public/img/computer.jpg",
    "name": "罗技MX Keys键盘",
    "category": "电脑配件",
    "price": 699,
    "count": 154,
    "status": "在售",
    "createdAt": "2023-01-25"
  },
  {
    "id": "10",
    "img": "public/img/phone.jpg",
    "name": "OPPO Find X6 Pro",
    "category": "智能手机",
    "price": 6499,
    "count": 33,
    "status": "在售",
    "createdAt": "2023-05-17"
  },
  {
    "id": "11",
    "img": "public/img/p1.jpg",
    "name": "Apple AirPods Pro 2",
    "category": "耳机",
    "price": 1899,
    "count": 201,
    "status": "在售",
    "createdAt": "2023-02-14"
  },
  {
    "id": "12",
    "img": "public/img/computer.jpg",
    "name": "华硕ROG Zephyrus G14",
    "category": "笔记本电脑",
    "price": 10999,
    "count": 19,
    "status": "在售",
    "createdAt": "2023-07-01"
  },
  {
    "id": "13",
    "img": "public/img/computer.jpg",
    "name": "明基PD2700U显示器",
    "category": "电脑配件",
    "price": 3699,
    "count": 0,
    "status": "缺货",
    "createdAt": "2023-04-22"
  },
  {
    "id": "14",
    "img": "public/img/phone.jpg",
    "name": "vivo X90 Pro+",
    "category": "智能手机",
    "price": 6999,
    "count": 47,
    "status": "在售",
    "createdAt": "2023-06-05"
  },
  {
    "id": "15",
    "img": "public/img/p1.jpg",
    "name": "Sony WF-1000XM4",
    "category": "耳机",
    "price": 1599,
    "count": 118,
    "status": "在售",
    "createdAt": "2023-03-11"
  }
]);

const tableRef = ref(null);
const selectedId = ref(null);
const selectedRows = ref([]);
const categoryFilter = ref('all');
const searchValue = ref('');
const dialogVisible = ref(false);
const dialogTitle = ref('添加商品');
const isEditing = ref(false);

const pageSize = ref(10);
const currentPage = ref(1);
const total = computed(() => filteredGoods.value.length);
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredGoods.value.slice(start, end); // 使用筛选后的数据
});

const handleCurrentChange = (page) => {
  currentPage.value = page;
}

// 获取所有唯一类别
const uniqueCategories = computed(() => {
  const categories = new Set();
  goods.value.forEach(item => categories.add(item.category));
  return Array.from(categories);
});

// 类别筛选器选项
const categoryFilters = computed(() => {
  return uniqueCategories.value.map(category => ({
    text: category,
    value: category
  }));
});

// 处理类别筛选
const handleCategoryFilter = (command) => {
  categoryFilter.value = command;
  currentPage.value = 1; // 重置为第一页
  tableRef.value.clearFilter();
};

// 类别筛选方法
const filterCategory = (value, row) => {
  return row.category === value;
};

// 处理单选框变化
const handleRadioChange = (row) => {
  console.log('单选选中:', row);
  // 这里可以添加单选处理逻辑
};

// 处理多选框变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
  console.log('多选选中:', rows);
  // 这里可以添加多选处理逻辑
};

// 计算属性 - 过滤商品（添加类别筛选）
const filteredGoods = computed(() => {
  let result = goods.value;

  // 应用类别筛选
  if (categoryFilter.value !== 'all') {
    result = result.filter(item => item.category === categoryFilter.value);
  }

  // 应用搜索筛选
  if (searchValue.value) {
    const search = searchValue.value.toLowerCase();
    result = result.filter(item =>
      item.name.toLowerCase().includes(search) ||
      item.category.toLowerCase().includes(search) ||
      item.status.toLowerCase().includes(search)
    );
  }

  return result;
});

// 获取图片路径（处理本地路径）
const getImagePath = (imgPath) => {
  // 如果已经是完整URL，直接返回
  if (imgPath.startsWith('http')) {
    return imgPath;
  }

  // 处理本地路径
  if (imgPath.startsWith('public/')) {
    return imgPath.replace('public/', '/');
  }

  return imgPath;
};

const form = reactive({
  id: '',
  img: '',
  name: '',
  category: '',
  price: 0,
  count: 0,
  status: '',
  createdAt: ''
});



// 搜索输入处理
const handleSearchInput = () => {
  currentPage.value = 1; // 重置为第一页
  clearTimeout(searchTimer.value);
  searchTimer.value = setTimeout(() => { }, 300);
};
// 清除搜索
const handleSearchClear = () => {
  searchValue.value = '';
};

// 添加防抖计时器
const searchTimer = ref(null);

// 清空表单
const clearForm = () => {
  form.id = '';
  form.img = '';
  form.name = '';
  form.category = '';
  form.price = 0;
  form.count = 0;
  form.status = '';
  form.createdAt = '';
};

// 自定义图片上传处理
const handleImageUpload = (options) => {
  const file = options.file;
  const reader = new FileReader();

  reader.onload = (e) => {
    // 这里只是将图片转换为Base64存储在内存中
    // 实际项目中应该上传到服务器并返回URL
    form.img = e.target.result;
  };

  reader.readAsDataURL(file);
};

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
};

// 删除商品
const handleDelete = (index, row) => {
  ElMessageBox.confirm(`确定要删除 "${row.name}" 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    goods.value = goods.value.filter(item => item.id !== row.id);
    ElMessage.success('删除成功!');
  }).catch(() => { });
};

// 添加商品
const handleAdd = () => {
  dialogTitle.value = '添加商品';
  isEditing.value = false;
  clearForm();
  form.img = '/img/default.jpg'; // 设置默认图片
  dialogVisible.value = true;
};

// 编辑商品
const handleEdit = (index, row) => {
  dialogTitle.value = '编辑商品';
  isEditing.value = true;
  Object.assign(form, {
    ...row,
    img: row.img // 保持原图片路径
  });
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = () => {
  if (!form.name || !form.category || !form.price) {
    ElMessage.warning('请填写必填字段');
    return;
  }

  if (isEditing.value) {
    const index = goods.value.findIndex(item => item.id === form.id);
    if (index !== -1) {
      // 保持原图片路径，除非用户上传了新图片
      const originalImg = goods.value[index].img;
      goods.value[index] = {
        ...form,
        img: form.img.startsWith('data:image') ? originalImg : form.img
      };
      ElMessage.success('编辑成功!');
    }
  } else {
    // 生成唯一ID
    const ids = goods.value.map(item => parseInt(item.id));
    const newId = ids.length > 0 ? String(Math.max(...ids) + 1) : '1';

    goods.value.push({
      ...form,
      id: newId,
      // 如果没有上传图片，使用默认图片
      img: form.img || '/img/default.jpg'
    });
    ElMessage.success('添加成功!');
  }
  dialogVisible.value = false;
};
</script>

<style scoped>
.category-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

/* 确保表头高度一致 */
.el-table__header th {
  padding: 12px 0;
}

/* 调整下拉图标位置 */
.category-header .el-dropdown {
  margin-left: 8px;
  display: flex;
  align-items: center;
}

/* 保持表头文本与其他列一致 */
.category-header span {
  flex: 1;
  text-align: left;
}

.table-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.add-button {
  height: 40px;
}

.goods-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.no-image,
.image-error {
  width: 60px;
  height: 60px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }

  .search-input {
    max-width: 100%;
  }
}

.pagination {
  margin-top: 20px;
  /* 让分页居中 */
  display: grid;
  justify-items: center;
}
</style>